//@ sourceURL=changeApply.js 
CommonUtils.regNamespace("com.im.changeApply");
com.im.changeApply.invoke = function() {
	var param = {
		pageNumber: 1,
	    pageSize: 20
	};
    var client = new com.im.common.ajax();
    var operType = "";
    var changeApply;
    var tmpfiles;//文件上传下载
    function _init() {
        //加载列表信息
    	_initDataList();
    	//重置按钮
    	$('#ResetBtn').click(function (){
    		_resetSearchInfo();
    	});
        //查询按钮
        $("#SearchBtn").click(function(){
        	_loadDataList(true);
        });
        //新增编辑保存按钮
        $("#saveBtn").click(function(){
        	_save();
        });
        //选择文件
        $('#choseFile').change(function (){
        	var reg = /[^\\\/]*[\\\/]+/g;
        	$('#fileName').val($(this).val().replace(reg, ''));
        });
        //上传文件
        $('#upLoadFile').click(function (){
        	if($('#choseFile').val() == ''){
        		toastr.error("请选择文件");
        		return false;
        	}
        	if($('#choseFile').val().indexOf('.xls') == -1 && $('#choseFile').val().indexOf('.xlsx') == -1){
        		toastr.error("请Excel选择文件");
        		return false;
        	}
            var targetUrl = $("#folderForm").attr("action");
            var data = new FormData($( "#folderForm" )[0]);
             $.ajax({
              type:'post',
              url:targetUrl,
              cache: false,    //上传文件不需缓存
              processData: false, //需设置为false。因为data值是FormData对象，不需要对数据做处理
              contentType: false, //需设置为false。因为是FormData对象，且已经声明了属性enctype="multipart/form-data"
              data:data,
              dataType:'json',
              success:function(data){
            	  toastr.success('请求成功');
            	  $("#choseFileModal").modal("hide");
              },
              error:function(){
            	  toastr.error("请求失败")
              }
             })
        });
        //复选框
        $('input[type="checkbox"].minimal, input[type="radio"].minimal').iCheck({
          checkboxClass: 'icheckbox_minimal-blue',
          radioClass   : 'iradio_minimal-blue'
        });
        //所属规划-建设单位-实施项目
        $("#searchOrgName").project2unit2itemCommpent({
            elmIdPlanTypeSel : "searchPlanProjClass",
            elmIdUnitSel : "searchOrgName",//组织单位下拉元素
            elmIdItemSel : "searchImpleProjName",//实施项目下拉元素
            orgType : "10",//初始化单位时，单位类型
            callbackFunc: function (callBackType, ret) {//下拉框值改变时回调
                _loadDataList(true);
            }
        });
        //下拉框
        $('.select2').select2();
       //总额计算
        $('#amount,#otherCharge,#unitPrice').keyup(function (){
        	var amount = Number($('#amount').val());
        	var unitPrice = Number($('#unitPrice').val());
        	var otherCharge = Number($('#otherCharge').val());
        	$('#itemTotal').val(amount*unitPrice+otherCharge);
        });
        //验证
        _formValidator();
        //重置验证
        $('#addEditModal').on('hidden.bs.modal', function() {
        	_reset();
        });
    };
    //重置搜索条件
    function _resetSearchInfo(){
    	$('#searchImpleProjName,#searchContractCode,#searchContractName').val('');
    }
    //更新数据列表
    function _loadDataList(pageNumber){
    	var impleProjName = $("#searchImpleProjName").val();
    	var contractCode = $("#searchContractCode").val();
    	var contractName = $("#searchContractName").val();
        param.impleProjName = impleProjName;
        if(contractCode == ''){
        	delete param.contractCode;
        }else{
        	param.contractCode = contractCode;
        }
        param.contractName = contractName;
        if(pageNumber){
    		param.pageNumber = 1;
            $('#changeApplyList').datagrid("load",param);
        }else{
    	   $('#changeApplyList').datagrid("reload",param);
        }
    }
    //新增编辑(保存按钮)
    function _save(){
    	$("#changeApplyForm").data("bootstrapValidator").validate();
    	var flag = $("#changeApplyForm").data("bootstrapValidator").isValid();
    	if(flag){
	    	var saveparam={};
	    	saveparam.contractItemId= $("#contractItemId").val();
	    	saveparam.conItemId= $("#conItemId").val();
	    	saveparam.contractItemName= $("#contractItemName").val();
	    	saveparam.contractClauseId= $("#contractClauseId").val();
	    	saveparam.contItemChangeId= $("#contItemChangeId").val();
	    	saveparam.amount= $("#amount").val();
	    	saveparam.unitPrice= $("#unitPrice").val();
	    	saveparam.itemTotal= $("#itemTotal").val();
	    	saveparam.description= $("#description").val();
	    	saveparam.itemTotal= $("#itemTotal").val();
	    	saveparam.otherCharge= $("#otherCharge").val();
	    	saveparam.status= $("#status").val();
	    	saveparam.optype= operType;
	    	client.callAsFile(tmpfiles.newly, function(fileRes) {
	             if(fileRes.success){
	            	 saveparam.addFiles = fileRes.result;
	            	 saveparam.delFiles = tmpfiles.del;
	            	 var result = client.callAsJson("contractService/saveOrUpdateContractIteChange", saveparam);
	     	         if(result.resultCode=='0'){
	     	        	$("#addEditModal").modal("hide");
	     		        toastr.success("保存成功！");
	     	    		_loadDataList();
	     	    	 }else {
	     	            toastr.error("服务器忙！请稍后再试！"+result.resultMsg);
	     	         }
	             }else{
	                 toastr.error('文件服务器忙！请稍后再试！');
	             }
	        });
    	}
    }
  //验证
    function _formValidator(){
    	$("#changeApplyForm").bootstrapValidator({
    	    feedbackIcons: {
    	      valid: 'glyphicon glyphicon-ok',
    	      invalid: 'glyphicon glyphicon-remove',
    	      validating: 'glyphicon glyphicon-loadData'
    	    },
    	    excluded: [':hidden', ':not(:visible)'],
    	    fields: {
    	    	contractItemName:{
    	    		validators: {
  	    	          notEmpty: {
  	    	            message: '分项名称不能为空'
  	    	          }
  	    	        }
    	    	},
    	    	amount: {
	    	        validators: {
	    	          notEmpty: {
	    	            message: '数量不能为空'
	    	          },
	    	          regexp: {
                          regexp: /^(\-)?\d+(\.\d+)?$/,
                          message: '数量只能包含负数符号/数字/小数点'
                      }
	    	        }
    	    	},
    	    	unitPrice: {
	    	        validators: {
	    	          notEmpty: {
	    	            message: '单价不能为空'
	    	          },
	    	          regexp: {
                          regexp: /^\d+(\.\d+)?$/,
                          message: '单价只能包含数字/小数点'
                      }
	    	        }
    	    	}
    	    }
    	  });
    }
    //重置验证
    function _reset(){
    	$("#changeApplyForm").data('bootstrapValidator').destroy();
        $('#changeApplyForm').data('bootstrapValidator', null);
        _formValidator();
    }
    //上传excel
    function _uploadExcel(index){
    	$('#choseFileModal').modal("show");
    	$('#fileName,#choseFile').val('');
    	contractService = $('#changeApplyList').datagrid('getData').rows[index];
    	$('#contractClauseIdUp').val(contractService.contractClauseId);
    }
    //新增操作
    function _add(index){
    	operType=0;
    	 $("#addEditModal .modal-title").html("合同分项增加");
    	 changeApply = $('#changeApplyList').datagrid('getData').rows[index];
	   	  var result = client.callAsJson("contractService/queryContractItemDetail", {'contractItemId':changeApply.contractItemId,'conItemId':changeApply.conItemId});
	   	  if (result.resultCode=="0") {
	             if(result.result!= null){
	           	  _show(result.result,'add');
	             }
	         } else {
	             toastr.error("服务器忙！请稍后再试！"+result.resultMsg);
	         }
         $("#addEditModal").modal("show");
    }
    //删除操作
    function _delete(index){
    	com.im.common.confirm("确定要删除吗？", null, function () {
    	  changeApply = $('#changeApplyList').datagrid('getData').rows[index];
    	  var result = client.callAsJson("contractService/deleteContractItemChange", {'contItemChangeId':changeApply.contItemChangeId,'conItemId':changeApply.conItemId});
    	  if (result.resultCode=="0") {
  	          toastr.success("删除成功！");
    		  _loadDataList();
          } else {
              toastr.error("服务器忙！请稍后再试！"+result.resultMsg);
          }
    	});
    }
    //编辑操作
    function _edit(index){
    	operType=1;
    	 $("#addEditModal .modal-title").html("合同分项修改");
    	 changeApply = $('#changeApplyList').datagrid('getData').rows[index];
    	  var result = client.callAsJson("contractService/queryContractItemDetail", {'contractItemId':changeApply.contractItemId,'conItemId':changeApply.conItemId,'contItemChangeId':changeApply.contItemChangeId});
    	  if (result.resultCode=="0") {
              if(result.result!= null){
            	  _show(result.result,'edit');
              }
          } else {
              toastr.error("服务器忙！请稍后再试！"+result.resultMsg);
          }
         $("#addEditModal").modal("show");
    }
    //新增编辑模态框数据初始化
    function _show(changeApply,type){
    	var fileList = changeApply.files;
        $.each(fileList,function (index,item){
            fileList[index].fileSuffix = item.attachFullName;
            fileList[index].uploadName = item.attachFullName;
            fileList[index].filePath = item.attachPath;
            fileList[index].uploadId = item.uploadId;
        });
        var file = new com.im.common.file();
        tmpfiles = file.activate(1,fileList);
    	if(type == 'add'){
    		$("#contractCode").val(changeApply.contractCode);
	         $("#contractName").val(changeApply.contractName);
	         $("#contractItemId").val(changeApply.contractItemId);
	         $("#conItemId").val(changeApply.conItemId);
	         $("#contractClauseId").val(changeApply.contractClauseId);
	         $("#clausename").val(changeApply.contractClauseName);
             $("#contractItemName").val("");
             $("#amount").val("");
             $("#unitPrice").val("");
             $("#otherCharge").val("");
             $("#itemTotal").val("");
             $("#description").val("");
    	}else{
	   		 $("#contractCode").val(changeApply.contractCode);
	         $("#contractName").val(changeApply.contractName);
	         $("#conItemId").val(changeApply.conItemId);
	         $("#status").val(changeApply.status);
	         $("#contractClauseId").val(changeApply.contractClauseId);
	         $("#contractItemId").val(changeApply.contractItemId);
	         $("#clausename").val(changeApply.contractClauseName);
	         $("#contractItemName").val(changeApply.contractItemName);
	         $("#contractItemId").val(changeApply.contractItemId);
	         $("#clausename").val(changeApply.contractClauseName);
	         $("#contItemChangeId").val(changeApply.contItemChangeId);
	         $("#amount").val(changeApply.amount);
	         $("#unitPrice").val(changeApply.unitPrice);
	         $("#otherCharge").val(changeApply.otherCharge);
	         $("#itemTotal").val(changeApply.itemTotal);
	         $("#description").val(changeApply.description);
    	}
    }
    //合并单元格
    function mergeCellsByField(tableID, fldList,other) {
    	var Arr = fldList.split(",");  
        var dg = $('#' + tableID);  
        var fldName;  
        var RowCount = dg.datagrid("getRows").length;  
        var span;  
        var PerValue = "";  
        var CurValue = "";  
        var length = Arr.length - 1;  
        var otherNum = 1;
        for (i = length; i >= 0; i--) {  
            fldName = Arr[i];  
            PerValue = "";  
            span = 1;  
            for (row = 0; row <= RowCount; row++) {  
                if (row == RowCount) {  
                    CurValue = "";  
                }  
                else {  
                    CurValue = dg.datagrid("getRows")[row][fldName];  
                }  
                if (PerValue === CurValue) {  
                    span += 1;  
                }  
                else {  
                    var index = row - span;  
                    dg.datagrid('mergeCells', {  
                        index: index,  
                        field: fldName,  
                        rowspan: span,  
                        colspan: null  
                    });  
                    if(fldName == 'contractCode'){
                        var name = other.split(","); 
                        $.each(name,function (i,item){
                        	dg.datagrid('mergeCells', {  
                                index: index,  
                                field: item,  
                                rowspan: span,  
                                colspan: null  
                            });
                        });
                    }
                    span = 1;  
                    PerValue = CurValue;  
                }  
            }  
            otherNum++;
        }  
    }

    //初始化表格数据
    function _initDataList(){
    	var columns=[[
    	    {field:'index',title:"序号",width:40,resizable:true,
    	              	formatter: function(value,row,index){
    	                      return  index+1;
    	                  }
    	    },
    	    {field:'impleProjName',title:"实施项目名称",width:120,resizable:true,align:'center'},
    	    {field:'contractCode',title:"合同编号",width:120,resizable:true,align:'center'},
    	    {field:'contractName',title:"合同名称",width:100,resizable:true,align:'center'},
    	    {field:'contractType',title:"合同类型",width:80,resizable:true,align:'center'},
    	    {field:'contractTotal',title:"总金额<br/>（万元）",resizable:true,align:'center'},
    	    {field:'contractClauseName',title:"支付条款",width:100,align:'center',
    	        formatter: function(value,row,index){
    	            return  '<div>'+value+'</div>'+	
    	            		'<a href="javascript:; "onclick="com.im.changeApply.invoke.add(\''+index+'\')" title="增加"><i class="fa fa-plus"></i></a> ';
//    	                    '<a href="javascript:; "onclick="com.im.changeApply.invoke.uploadExcel(\''+index+'\')" title="导入"><i class="fa fa-upload"></i></a>';
    	    }},
    	    {field:'contractItemName',title:"分项名称",width:100,resizable:true,align:'center'},
    	    {field:'amount',title:"数量",width:60,resizable:true,align:'center'},
    	    {field:'unitPrice',title:"单价<br/>（万元）",resizable:true,align:'center'},
    	    {field:'otherCharge',title:"其它费用<br/>（万元）",resizable:true,align:'center'},
    	    {field:'itemTotal',title:"分项总额<br/>（万元）",resizable:true,align:'center'},
    	    {field:'statusCd',title:"状态",width:80,resizable:true,align:'center'},
        	{field:'description',title:"备注",width:160,resizable:true,align:'center'},
        	{field:'files',title:"文件",width:160,resizable:true,align:'center', formatter: function(value,row,index){
        		if(value.length > 0){
        			var str = '';
        			$.each(value,function (index,item){
        				if(index == 0){
        					str = item.attachFullName;
        				}else{
            				str = str + '<br/>' + item.attachFullName;
        				}
        			});
        			return str;
        		}else{
        			return '';
        		}
			}},
    	    {field:'operation',title:"操作",width:80,align:'center',
    	        formatter: function(value,row,index){
    	        	if(row.status == 20 || row.status == 10){
    	        		return  '<a href="javascript:; "onclick="com.im.changeApply.invoke.editList(\''+index+'\')" title="修改"><i class="fa fa-edit"></i></a> '+
	                            '<a href="javascript:; "onclick="com.im.changeApply.invoke.deleteList(\''+index+'\')" title="删除"><i class="fa fa-trash"></i></a>';
    	        	}
//    	        	else{
//    	        		return  '<a href="javascript:; "onclick="com.im.changeApply.invoke.editList(\''+index+'\')" title="修改"><i class="fa fa-edit"></i></a>' ;
//    	        	}
    	    }},
    	]];
    	$('#changeApplyList').datagrid({
    	    url:'/InfoManageWeb/contractService/queryCanChangeContractItemList',
    	    method:'post',
    	    dataType : 'json',
    	    queryParams:param,
    	    pagination:true,
    	    nowrap:false,
    	    fitColumns:true,
    	    columns:columns,
    	    loadMsg:'数据加载中，请耐心等待',
    	    onBeforeLoad : function(param){
	    	    for (var key in param) {
		    	    if(key=="rows"){
		    	    	delete param[key];
		    	    }
		    	}
    	    },
    	    loadFilter:function(data){
    	      if(data.resultCode!=0){
    	        toastr.error(data.resultCode);
    	        return null;
    	      }else{
    	        return data.result;
    	      }
    	    },
    	    onLoadSuccess: function (data) {
                if (data.rows.length > 0) {
                	mergeCellsByField('changeApplyList', "impleProjName,contractCode,impleProjName,contractName,contractType",'contractClauseName,contractTotal');
                }
            }
    	});
    	var p = $('#changeApplyList').datagrid('getPager');
    	  $(p).pagination({
    	    pageSize: 20,
    	    pageList: [10,20,30],
    	    beforePageText: '第',
    	    afterPageText: '页    共 {pages}  页',
    	    displayMsg: '当前显示 {from} - {to} 条记录 共 {total}  条记录',
    	    onSelectPage:function(pageNumber, pageSize){
    	      param.pageNumber=pageNumber;
    	      param.pageSize=pageSize;
    	      	var impleProjName = $("#searchImpleProjName").val();
    	    	var contractCode = $("#searchContractCode").val();
    	    	var contractName = $("#searchContractName").val();
    	        param.impleProjName = impleProjName;
    	        if(contractCode == ''){
    	        	delete param.contractCode;
    	        }else{
    	        	param.contractCode = contractCode;
    	        }
    	        param.contractName = contractName;
    	      $('#changeApplyList').datagrid('reload',param);
    	    }
    	  });
    }

	return {
		init : _init,
		deleteList : _delete,
		editList : _edit,
		add : _add,
		uploadExcel: _uploadExcel
	}
}();

$(function() {
	com.im.changeApply.invoke.init();
});
